<template>
  <div class="main_friend_right_chat" v-show="isShowChatBox">
    <div class="main_friend_right_chat_header">
      <div class="main_friend_right_chat_header_title">
        <div class="main_friend_right_chat_header_content">{{ friendInfo.user?.nickname }}</div>
      </div>
    </div>
    <div class="main_friend_right_chat_body">
      <a-button @click="handleFriendChat" class="main_friend_right_chat_send" type="primary">
        发送
      </a-button>
      <div class="main_friend_right_chat_one" id="scrollWatch">
        <div class="main_friend_right_chat_one_for">
          <a-spin :spinning="spinning" :tip="'加载中'" :delay="100">
            <div v-for="item in friendChatContentList" :key="item.id">
              <div v-if="item.userId===chat.userId" class="main_friend_right_chat_one_for_item_left">
                <div>
                  <div class="main_friend_right_chat_one_for_item_left_nickname">{{ item.nickname }}</div>
                  <div v-dompurify-html="item.content" class="main_friend_right_chat_one_for_item_left_content"></div>
                </div>
                <img :src="item.avatar" class="main_friend_right_chat_one_for_item_left_avatar" alt="头像">
              </div>
              <div v-else class="main_friend_right_chat_one_for_item_right">
                <img :src="item.avatar" class="main_friend_right_chat_one_for_item_right_avatar" alt="头像">
                <div>
                  <div class="main_friend_right_chat_one_for_item_right_nickname">{{ item.nickname }}</div>
                  <div v-dompurify-html="item.content" class="main_friend_right_chat_one_for_item_right_content"></div>
                </div>
              </div>
            </div>
          </a-spin>
        </div>
      </div>
      <div class="main_friend_right_chat_two">
        <Editor @sendContentToFriendChat="receiveChildContent" @keyup="deleteSurplusImg"
                class="main_friend_right_chat_two_editor"/>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import Publish from 'pubsub-js'
import {nextTick, ref} from "vue";
import Editor from '@/components/myRichText/friendChatEditor/index.vue'
import {deleteImg} from "@/api/home/answer";
import {friendChat, getUserFriendChatContent} from "@/api/personalCenter/myFriends";
import {Chat} from "@/model/personalCenter/myFriends";
// @ts-ignore
import cookie from 'js-cookie'
import {getText, isNull} from "@/utils/checkoutEditor";
import {watch} from 'vue';
import {message} from "ant-design-vue";

//是否显示加载中
const spinning = ref<boolean>(false);

//是否显示聊天框
const isShowChatBox = ref<boolean>(false)

//当前用户的好友聊天内容列表
const friendChatContentList = ref()

//监听聊天列表长度的变化，让聊天框自动到最底部(即获取最新的聊天内容)
watch(() => friendChatContentList.value, () => {
  nextTick(() => {
    let ele: any = document.getElementById('scrollWatch')
    ele.scrollTop = ele.scrollHeight
  })
}, {
  deep: true
})

//获取当前用户的好友聊天内容
const handleUserFriendChatContent = () => {
  if (chat.value.friendId != 0) {
    getUserFriendChatContent(chat.value.userId, chat.value.friendId).then((res) => {
      friendChatContentList.value = res.data.data.list
      const regex = new RegExp('<img', 'gi')
      friendChatContentList.value.map((item: any) => {
        item.content = item.content.replace(regex, `<img style="max-width: 100%; height: auto"`)
      })
    })
  }
}

//聊天所需的参数
const chat = ref<Chat>({
  userId: 0,
  nickname: '',
  avatar: '',
  friendId: 0,
  friendNickname: '',
  friendAvatar: '',
  content: ''
})

//好友的信息
const friendInfo = ref({
      user: {
        id: 0,
        nickname: '',
        avatar: ''
      }
    }
)

//朋友聊天
const handleFriendChat = () => {
  //校验消息是否为空
  let checkContent = getText(chat.value.content)
  if (isNull(checkContent)) {
    message.warn('内容不能为空！')
  } else {
    if (chat.value.userId == 0 || chat.value.friendId == 0) {
      message.error('网络异常，请稍后重试！')
    } else {
      friendChat(chat.value).then(() => {
        //清除富文本编辑器内容
        Publish.publish('clearContentToFriendChat')
        chat.value.content = '<p></p>'
        handleUserFriendChatContent()
      })
    }
  }
}

//接收好友聊天的内容
const receiveFriendChatContent = () => {
  Publish.subscribe('handleFriendChat', (funName: string, msg: any) => {
    friendInfo.value = msg
    chat.value.friendId = friendInfo.value.user.id
    chat.value.friendNickname = friendInfo.value.user.nickname
    chat.value.friendAvatar = friendInfo.value.user.avatar
    spinning.value = true
    isShowChatBox.value = true
    handleUserFriendChatContent()
    setTimeout(() => {
      let ele: any = document.getElementById('scrollWatch')
      ele.scrollTop = ele.scrollHeight
      spinning.value = false
    }, 1000)
  })
}

//删除的图片名数组,防止垃圾图片残留
const imgDelName = ref<any>([])

//接收子组件传过来的值
const receiveChildContent = (arr: string) => {
  chat.value.content = arr[0]
  imgDelName.value = arr[1]
}

//按删除键时并且多余的图片不为0时执行
const deleteSurplusImg = (e: any) => {
  if (e.keyCode === 8 && imgDelName.value.length != 0) {
    //删除多余图片
    deleteImg(imgDelName.value).then(() => {
    })
  }
}

//从cookie中获取用户信息
const getUserinfo = () => {
  chat.value.userId = JSON.parse(cookie.get('userinfo')).id
  chat.value.nickname = JSON.parse(cookie.get('userinfo')).nickname
  chat.value.avatar = JSON.parse(cookie.get('userinfo')).avatar
}

getUserinfo()
receiveFriendChatContent()
</script>

<style lang="less" scoped>
.main_friend_right_chat {
  margin-left: 6%;
  margin-top: 1%;

  .main_friend_right_chat_header {
    width: 85%;
    margin-bottom: 1%;

    .main_friend_right_chat_header_title {
      margin: auto;
      width: fit-content;

      .main_friend_right_chat_header_content {
        width: 120%;
        text-align: center;
        font-size: 30px;
        font-weight: bold;
        border-radius: 25px;
        background-image: linear-gradient(to top, #d9afd9 0%, #97d9e1 100%);
      }
    }
  }

  .main_friend_right_chat_body {
    width: 85%;
    margin-right: 10%;

    height: 75vh;
    background-color: white;

    .main_friend_right_chat_one {
      height: 65%;
      overflow-y: scroll;

      .main_friend_right_chat_one_for {
        .main_friend_right_chat_one_for_item_left {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 10px;

          .main_friend_right_chat_one_for_item_left_avatar {
            width: 80px;
            height: 80px;
          }

          .main_friend_right_chat_one_for_item_left_nickname {
            margin-top: 10px;
            margin-bottom: 15px;
            font-weight: bold;
            margin-right: 10px;
            text-align: right;
          }

          .main_friend_right_chat_one_for_item_left_content {
            //margin-left: 50px;
            margin-right: 10px;
            word-wrap: break-word;
            max-width: 500px;
          }
        }

        .main_friend_right_chat_one_for_item_right {
          display: flex;
          //margin-bottom: 5px;

          .main_friend_right_chat_one_for_item_right_avatar {
            width: 80px;
            height: 80px;
          }

          .main_friend_right_chat_one_for_item_right_nickname {
            margin-top: 10px;
            font-weight: bold;
            margin-left: 10px;
          }

          .main_friend_right_chat_one_for_item_right_content {
            margin-top: 15px;
            margin-left: 10px;
            word-wrap: break-word;
          }
        }
      }
    }

    .main_friend_right_chat_two_editor {
      .main_friend_right_chat_send {
        position: absolute;
      }
    }

    .main_friend_right_chat_send {
      position: absolute;
      margin-left: 90vh;
      margin-top: 70vh;
      z-index: 99999;
    }
  }
}

//滚动条透明
::-webkit-scrollbar {
  height: 0;
  width: 0;
  color: transparent;
}
</style>